package com.itheima.day30.demo05;

import com.itheima.day30.demo02.DruidUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class test {
    @Test
    public void show() {
        Connection con = null;
        Statement stat = null;
        try {
            con = DruidUtils.getConnection();
            con.setAutoCommit(false);
            stat = con.createStatement();
            String sql = "insert into account values (null,'saber',10000),(null ,'arther',10000);";
            stat.addBatch(sql);
            final int[] ints = stat.executeBatch();
            if (ints[0] == 2) {
                con.commit();
            } else {
                con.rollback();
            }

        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DruidUtils.release(con, stat);
        }
    }

    @Test
    public void show2() {
        Connection con = null;
        Statement stat = null;
        try {
            con = DruidUtils.getConnection();
            con.setAutoCommit(false);
            stat = con.createStatement();
            String sql1 = "update account set money=money-1000 where aid=1;";
            String sql2 = "update account set money=money+1000 where aid=2;";
            stat.addBatch(sql1);
            //System.out.println(1/0);
            stat.addBatch(sql2);
            int[] ints = stat.executeBatch();
            if (ints[0] == 1 && ints[1] == 1) {
                con.commit();
                System.out.println("成功");
            } else {
                con.rollback();
                System.out.println("失败");
            }

        } catch (Exception e) {
            try {
                System.out.println("失败");
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DruidUtils.release(con, stat);
        }
    }
}
